﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Diagnostics;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.IO;
using System.Text;
using Microsoft.Win32;
using System.Drawing;
using System.Threading;
using System.Net;
using System.Runtime.InteropServices;
namespace Piao
{

    static class Program
    {
        private static Mutex mut = new Mutex(true, "train");

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {

            //var sb = Helper.GenerateOdata(Clipboard.GetText());
#if DEBUG
            
            MainForm mf = new MainForm();
            Application.Run(mf);
            return;
#endif


            if (!IsDotnet35Sp1Installed())
            {
                MessageBox.Show("需要安装 .netFX 3.5 SP1. Application exits.", "Warning");
                Process.Start("http://www.microsoft.com/downloads/zh-cn/details.aspx?FamilyID=ab99342f-5d1a-413d-8319-81da479ab0d7");
                return;
            }

            RegisterPreSetup();
            Register();

            Process.Start("iexplore.exe", UserOpration.URL_HOME);

        }


        /// <summary>
        /// remove all previous bho objects and update with current path.
        /// </summary>
        /// <param name="path"></param>
        private static void RegisterPreSetup()
        {
            string currentFileFolder = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            string installPath = @"SOFTWARE\microsoft\piao\RuntimeFolders";
            RegistryKey key = Registry.LocalMachine.OpenSubKey(installPath, true);
            if (key == null)
                key = Registry.LocalMachine.CreateSubKey(installPath);


            bool regvalueAlreadySet = false;
            var keys = key.GetValueNames();



            foreach (string k in keys)
            {
                string val = key.GetValue(k, "") as string;

                if (val != currentFileFolder)
                {
                    key.DeleteValue(k, false);

                    if (Directory.Exists(val))
                        Register(val, true);
                }
                else
                {
                    regvalueAlreadySet = true;
                }
            }

            if (!regvalueAlreadySet)
                key.SetValue(Guid.NewGuid().ToString().Substring(0, 5), currentFileFolder);
        }


        public static void Register(string fileFolder = "", bool uninstall = false)
        {
            fileFolder = string.IsNullOrEmpty(fileFolder) ?
                fileFolder = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) :
                fileFolder;

            string option = uninstall ? "/u" : "/codebase";
            string regasm = Path.GetFullPath(Path.Combine(Environment.ExpandEnvironmentVariables("%windir%"), @"Microsoft.NET\Framework\v2.0.50727\RegAsm.exe"));
            string arg = string.Format(@"/c {0}  {1} piao.exe ", regasm, option);
            Process proc = new Process();
            ProcessStartInfo psi = new ProcessStartInfo("cmd.exe");
            psi.CreateNoWindow = true;
            psi.UseShellExecute = false;
            psi.Arguments = arg;
            psi.WorkingDirectory = fileFolder;
            proc.StartInfo = psi;
            proc.Start();
            proc.WaitForExit(5000);
        }

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {

            MessageBox.Show(
#if DEBUG
e.Exception.ToString()
#else
e.Exception.Message
#endif
, "Error", MessageBoxButtons.OK);
        }


        static bool IsDotnet35Sp1Installed()
        {

            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5");
            if (key != null)
            {
                int sp = (int)key.GetValue("SP", -1);
                return sp > 0;
            }
            return false;
        }
    }
}
